package com.utra.hellshan.upload.UI;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.utra.hellshan.upload.NetTool.NetClient;
import com.utra.hellshan.upload.OtherTools.ServiceTool;
import com.utra.hellshan.upload.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import services.StatusService;

import static android.Manifest.permission.READ_CONTACTS;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static java.lang.Thread.sleep;

/**
 * A login screen that offers login via email/password.
 */
public class LogIn extends Activity implements LoaderCallbacks<Cursor> {


    /**
     * Id to identity READ_CONTACTS permission request.
     */
    private static final int REQUEST_READ_CONTACTS = 0;

    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[]{
            "foo@example.com:hello", "bar@example.com:world"
    };
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    private Socket socket;
    private BufferedReader input;      //socket输入流
    private PrintStream output;          //socket输出流


    public static String TYPE_REGISTER = "TYPE_REGISTER";    //注册
    public static String TYPE_LOGIN = "TYPE_LOGIN";   //登录
    public final static String SUCCESS = "SUCCESS" ;

    ProgressDialog progressDialog;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            super.handleMessage(msg);

            progressDialog.cancel();

            if(msg.getData().get("result").equals("LOGIN_SUCCESS"))
            {
                Toast.makeText(LogIn.this , "登陆成功" , Toast.LENGTH_SHORT).show();


                try {
                    if(input != null)
                        input.close();
                    if(output != null)
                        output.close();
                    if(socket!= null && socket.isConnected())
                        socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }



                startActivity(new Intent(LogIn.this, mapAvtivity.class));
                StatusService.setLoggedin(true);
                finish();

            }else if(msg.getData().get("result").equals("REGISTER_SUCCESS"))
            {
                Toast.makeText(LogIn.this , "注册成功，请登录" , Toast.LENGTH_SHORT).show();
                change_back();
            }else if(msg.getData().get("result").equals("LOGIN_FAIL"))
            {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }else if(msg.getData().get("result").equals("REGISTER_FAIL"))
            {
                mEmailView.setError("该账号已被注册");
                mEmailView.requestFocus();
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("请稍等");
        progressDialog.setMessage("正在执行操作");
        progressDialog.setCancelable(false);


        requestPower();

/*
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Init();
                Looper.loop();
            }
        }).start();
*/

        if(ServiceTool.isServiceWork(this,"services.StatusService"))            //如果已经登录，直接跳转主界面
        {
            if(StatusService.GetLoginStatus() == true)
            {
                startActivity(new Intent(LogIn.this, mapAvtivity.class));
                Toast.makeText(this , "通过Login创建活动" , Toast.LENGTH_LONG).show();
                finish();
            }
            else
            {
                Toast.makeText(this , "用户未登录" , Toast.LENGTH_LONG).show();
            }
        }
        else
        {
            Intent intent = new Intent(this, StatusService.class);
            startService(intent);
            StatusService.setLoggedin(false);
        }






        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        populateAutoComplete();




        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);












    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }

        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PERMISSION_GRANTED) {
            return true;
        }

        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        String requestPermissionsResult = "";
        if (requestCode == 1) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PERMISSION_GRANTED) {
                } else {

                    new AlertDialog.Builder(this).setTitle("提示")//设置对话框标题

                            .setMessage("当前未获取必要权限(定位与IMEI)，无法启动，请手动赋予后再试")//设置显示的内容
                            .setMessage(requestPermissionsResult)

                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮


                                @Override

                                public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

                                    // TODO Auto-generated method stub

                                    finish();

                                }

                            }).show();//在按键响应事件中显示此对话框

                }
            }



        }
        //Toast.makeText(this, requestPermissionsResult, Toast.LENGTH_SHORT).show();
    }


    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {



        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();

                Init();
                Looper.loop();
            }
        }).start();

        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError("不能为空");
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            progressDialog.show();

            /**
             *
             *
             * 这里是登陆逻辑
             *
             *
             */
            //mAuthTask = new UserLoginTask(email, password);
            //mAuthTask.execute((Void) null);

            final String email_ = email;
            final String passwd_ = password;


            new Thread(new Runnable(){

                @Override
                public void run() {

                    try {
                        Thread.sleep((long) 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    String requestResult = "null";


                    try {
                        output.print(TYPE_LOGIN + "#" + email_ + "#" + passwd_ + "#" + "" + "\n");
                        String temp = input.readLine();
                        requestResult =  (temp.equals(SUCCESS))?"LOGIN_SUCCESS":"LOGIN_FAIL";
                    }catch (Exception e)
                    {
                        Toast.makeText(LogIn.this , "Server connect error \n  服务器通信出错,退出 " , Toast.LENGTH_LONG).show();
                        Log.e("19980" , e.getMessage());
                        finish();
                    }


                    bundle.putString("result",requestResult);
                    message.setData(bundle);
                    handler.sendMessage(message);

                    Looper.loop();
                }

            }).start();

        }
    }


    /*********************************************************************************/
    /***********              在这个函数里进行用户注册操作                 *************/
    /*********************************************************************************/

    public void register(View view)
    {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Init();
                Looper.loop();
            }
        }).start();

        setTitle("注册");

        Button button = (Button)findViewById(R.id.email_sign_in_button);
        button.setVisibility(View.INVISIBLE);

        Button button_1 = (Button)findViewById(R.id.button_register);
        button_1.setText("确认注册");

        Button button_2 = (Button)findViewById(R.id.button_return_login);
        button_2.setVisibility(View.VISIBLE);

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        final String email = mEmailView.getText().toString();
        final String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        if (TextUtils.isEmpty(password)) {
            mPasswordView.setError("不能为空");
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            Toast.makeText(LogIn.this,"请检查注册信息",Toast.LENGTH_LONG).show();
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            progressDialog.show();
            /*********************************************************************************/
            /***********                    进行实际注册操作                      *************/                      /*     完成    */
            /*********************************************************************************/



            new Thread(new Runnable(){

                @Override
                public void run() {


                    try {
                        Thread.sleep((long) 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    Looper.prepare();
                    Message message = new Message();
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    String requestResult = "null";


                    try {
                        output.print(TYPE_REGISTER + "#" + email + "#" + password + "#" + "" + "\n");
                        String temp = input.readLine();
                        requestResult =  (temp.equals(SUCCESS))?"REGISTER_SUCCESS":"REGISTER_FAIL";
                    }catch (Exception e)
                    {
                        Toast.makeText(LogIn.this , "Server connect error \n  服务器通信出错,退出 " , Toast.LENGTH_LONG).show();
                        Log.e("19980" , e.getMessage());
                        finish();
                    }


                    bundle.putString("result",requestResult);
                    message.setData(bundle);
                    handler.sendMessage(message);

                    Looper.loop();
                }

            }).start();

        }
    }


    public void change_back()
    {
        Button button = (Button)findViewById(R.id.email_sign_in_button);
        button.setVisibility(View.VISIBLE);

        Button button_1 = (Button)findViewById(R.id.button_register);
        button_1.setText("没有账号？注册一个");

        Button button_2 = (Button)findViewById(R.id.button_return_login);
        button_2.setVisibility(View.INVISIBLE);

        mPasswordView.setText("");
    }


    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> emails = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            emails.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }

        addEmailsToAutoComplete(emails);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LogIn.this,
                        android.R.layout.simple_dropdown_item_1line, emailAddressCollection);

        mEmailView.setAdapter(adapter);
    }


    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
        int IS_PRIMARY = 1;
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                sleep(2000);
            } catch (InterruptedException e) {
                return false;
            }

            /*********************************************************************************/
            /***********              在这个函数里进行登录匹配验证                 *************/                      /*     完成    */
            /*登录验证过程在服务器进行，
             * 服务器仅返回验证结果*/



            boolean login = false;



            return login;

            // TODO: register the new account here.

        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;

            /*********************************************************************************/
            /***********            在这个函数里进行登录结果动作处理               *************/                       /*    完成    */
            /*********************************************************************************/

            if (success) {

                Toast.makeText(LogIn.this , "登陆成功"  , Toast.LENGTH_SHORT).show();
                startActivity(new Intent(LogIn.this, mapAvtivity.class));
                StatusService.setLoggedin(true);
                finish();
            } else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }

    @Override
    protected void onDestroy() {
        Toast.makeText(this , "Login销毁" , Toast.LENGTH_LONG).show();
        super.onDestroy();
    }

    public void requestPower() {

        String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION ,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS ,
                Manifest.permission.ACCESS_FINE_LOCATION ,
                Manifest.permission.ACCESS_WIFI_STATE ,
                Manifest.permission.ACCESS_NETWORK_STATE ,
                Manifest.permission.READ_PHONE_STATE ,     //IMEI
                Manifest.permission.WRITE_EXTERNAL_STORAGE ,
                Manifest.permission.GET_ACCOUNTS ,
                Manifest.permission.READ_CONTACTS
        };

        ActivityCompat.requestPermissions(
                this,
                permissions,
                1);

    }



    /**
     * onRequestPermissionsResult方法重写，Toast显示用户是否授权
     */

    public void Init()    //只能用多线程访问网络
    {


        try
        {
            //if(socket != null && socket.isConnected())
            //   socket.close();
            //if()
            {
                socket = new Socket(InetAddress.getByName("20832l397n.51mypc.cn") , 59293);       ///链接用户登录服务器\
                input =  new BufferedReader(new InputStreamReader(socket.getInputStream()));                                      //读取输入
                output = new PrintStream(socket.getOutputStream());
            }


            //output = new OutputStreamWriter(socket.getOutputStream());            //输出数据用

        }catch(Exception e) //后期代码优化应细化异常处理

        {
            Toast.makeText(this , "Server connect error \n  无法连接服务器" , Toast.LENGTH_LONG).show();
            Toast.makeText(this , e.toString() , Toast.LENGTH_LONG).show();

        }



    }


}

